package com.wdb.common.configurer.subject;

import com.wdb.common.constant.Constant;
import com.wdb.common.util.HttpServletRequestUtils;
import com.wdb.common.util.StringUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.Objects;

public class SubjectProxyInterceptor implements RequestInterceptor {
    private String proxy_target;

    private String proxy_subject;

    @Override
    public void apply(RequestTemplate template) {

        HttpServletRequest request = HttpServletRequestUtils.getRequest();

//        if (Objects.nonNull(request)) {
//            Enumeration<String> headerNames = request.getHeaderNames();
//            if (Objects.nonNull(headerNames)) {
//                while (headerNames.hasMoreElements()) {
//                    String name = headerNames.nextElement();
//
//                    Enumeration<String> values = request.getHeaders(name);
//                    while (values.hasMoreElements()) {
//                        String value = values.nextElement();
//                        template.header(name, value);
//                    }
//                }
//            }
//        }

        String target = SubjectContext.getTarget();

        Long subject = SubjectContext.getSubject();

        if (StringUtils.isEmpty(target)) {
            target = SubjectTarget.INVOKE.name();

        }

        if (Objects.isNull(subject)) {
            subject = Constant.Context.Subject.INVOKE;
        }

        template.header(proxy_target, Base64.getEncoder().encodeToString(target.getBytes()));

        template.header(proxy_subject, Base64.getEncoder().encodeToString(subject.toString().getBytes()));
    }

    public void setProxy_target(String proxy_target) {
        this.proxy_target = proxy_target;
    }

    public void setProxy_subject(String proxy_subject) {
        this.proxy_subject = proxy_subject;
    }
}
